const { openDatabase } = require('../index');

function getDb() {
    return openDatabase();
}

function createDownload(job) {
    const db = getDb();
    const stmt = db.prepare(`
    INSERT INTO downloads (
      id, file_url, file_name, save_path, status,
      total_bytes, received_bytes, percent, speed_bps,
      error_code, error_message, created_at, updated_at
    ) VALUES (
      @id, @file_url, @file_name, @save_path, @status,
      @total_bytes, @received_bytes, @percent, @speed_bps,
      @error_code, @error_message, datetime('now'), NULL
    )
  `);
    stmt.run(job);
}

function updateDownload(jobId, fields) {
    const db = getDb();
    const keys = Object.keys(fields);
    if (keys.length === 0) return;
    const setSql = keys.map((k) => `${k}=@${k}`).join(', ');
    const stmt = db.prepare(`
    UPDATE downloads SET ${setSql}, updated_at = datetime('now') WHERE id = @id
  `);
    stmt.run({ id: jobId, ...fields });
}

function getById(jobId) {
    const db = getDb();
    return db.prepare('SELECT * FROM downloads WHERE id = ?').get(jobId);
}

function listByStatus(status, limit = 50, offset = 0) {
    const db = getDb();
    return db
        .prepare(
            'SELECT * FROM downloads WHERE status = ? ORDER BY created_at DESC LIMIT ? OFFSET ?'
        )
        .all(status, limit, offset);
}

function listAll(limit = 50, offset = 0) {
    const db = getDb();
    return db
        .prepare('SELECT * FROM downloads ORDER BY created_at DESC LIMIT ? OFFSET ?')
        .all(limit, offset);
}

module.exports = {
    createDownload,
    updateDownload,
    getById,
    listByStatus,
    listAll,
};


